#include "sqlautocomplete.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QStandardItemModel>
#include <QStandardItem>
#include <QStringList>
#include <QCompleter>
#include <QTextCursor>
#include <QSqlRecord>
#include <QDebug>

SqlAutoComplete::SqlAutoComplete(QObject *parent)
    : QObject(parent)
    , m_completer(new QCompleter(this))
{
    initializeKeywords();
    initializeFunctions();
    
    // 设置补全器属性
    m_completer->setCaseSensitivity(Qt::CaseInsensitive);
    m_completer->setCompletionMode(QCompleter::PopupCompletion);
    
    // 初始化补全模型
    updateCompletionModel();
}

void SqlAutoComplete::setDatabase(const QSqlDatabase &database)
{
    m_database = database;
    loadDatabaseObjects();
    updateCompletionModel();
}

void SqlAutoComplete::updateCompletionModel()
{
    // 合并所有补全项
    m_allCompletions.clear();
    m_allCompletions.append(m_keywords);
    m_allCompletions.append(m_functions);
    m_allCompletions.append(m_tables);
    
    // 添加列名（带表前缀）
    for (auto it = m_columns.constBegin(); it != m_columns.constEnd(); ++it) {
        const QString &tableName = it.key();
        const QStringList &columns = it.value();
        for (const QString &column : columns) {
            m_allCompletions.append(tableName + "." + column);
        }
    }
    
    // 为补全器设置模型
    m_completer->setModel(new QStringListModel(m_allCompletions, m_completer));
}

QCompleter* SqlAutoComplete::completer() const
{
    return m_completer;
}

QStringList SqlAutoComplete::getKeywords() const
{
    return m_keywords;
}

QStringList SqlAutoComplete::getFunctions() const
{
    return m_functions;
}

QStringList SqlAutoComplete::getTables() const
{
    return m_tables;
}

QStringList SqlAutoComplete::getColumns(const QString &tableName) const
{
    return m_columns.value(tableName, QStringList());
}

void SqlAutoComplete::initializeKeywords()
{
    m_keywords << "SELECT" << "FROM" << "WHERE" << "INSERT" << "UPDATE" << "DELETE" 
               << "CREATE" << "DROP" << "ALTER" << "TABLE" << "INDEX" << "VIEW" 
               << "TRIGGER" << "PROCEDURE" << "FUNCTION" << "DATABASE" << "SCHEMA"
               << "PRIMARY" << "KEY" << "FOREIGN" << "REFERENCES" << "CONSTRAINT" 
               << "UNIQUE" << "CHECK" << "DEFAULT" << "NOT" << "NULL" << "AND" 
               << "OR" << "IN" << "EXISTS" << "BETWEEN" << "LIKE" << "AS" << "ON" 
               << "JOIN" << "INNER" << "LEFT" << "RIGHT" << "OUTER" << "CROSS" 
               << "FULL" << "UNION" << "ALL" << "DISTINCT" << "GROUP" << "BY" 
               << "ORDER" << "HAVING" << "LIMIT" << "OFFSET" << "INTO" << "VALUES" 
               << "SET" << "ADD" << "COLUMN" << "TO" << "IF" << "ELSE" << "BEGIN" 
               << "END" << "WHEN" << "THEN" << "CASE" << "WITH" << "RECURSIVE" 
               << "OVER" << "PARTITION" << "ROW" << "ROWS" << "RANGE" << "PRECEDING" 
               << "FOLLOWING" << "CURRENT" << "FOR" << "ONLY" << "USING" << "RETURNING" 
               << "CASCADE" << "RESTRICT" << "TRUE" << "FALSE";
}

void SqlAutoComplete::initializeFunctions()
{
    // 通用SQL函数
    m_functions << "COUNT" << "SUM" << "AVG" << "MIN" << "MAX" << "ABS" << "ROUND" 
                << "CEIL" << "FLOOR" << "POWER" << "SQRT" << "MOD" << "COALESCE" 
                << "NULLIF" << "CAST" << "CONVERT" << "SUBSTRING" << "CONCAT" 
                << "LENGTH" << "UPPER" << "LOWER" << "TRIM" << "LTRIM" << "RTRIM" 
                << "REPLACE" << "DATE" << "TIME" << "YEAR" << "MONTH" << "DAY" 
                << "HOUR" << "MINUTE" << "SECOND" << "NOW" << "CURDATE" << "CURTIME" 
                << "DATEDIFF" << "DATEADD" << "EXTRACT" << "POSITION" << "CHAR_LENGTH" 
                << "OCTET_LENGTH" << "CURRENT_DATE" << "CURRENT_TIME" << "CURRENT_TIMESTAMP";
}

void SqlAutoComplete::loadDatabaseObjects()
{
    if (!m_database.isOpen()) {
        return;
    }
    
    m_tables.clear();
    m_columns.clear();
    
    // 获取表列表
    QStringList tables = m_database.tables();
    m_tables = tables;
    
    // 获取每个表的列信息
    for (const QString &table : tables) {
        QSqlRecord record = m_database.record(table);
        QStringList columns;
        for (int i = 0; i < record.count(); ++i) {
            columns.append(record.fieldName(i));
        }
        m_columns[table] = columns;
    }
}